<script setup>
import GoBack from "@/components/GoBackAndSearchNav.vue";
import {useRoute, useRouter} from 'vue-router'
import {ref, onBeforeMount} from 'vue'
import {getProductListRandomAPI} from "@/api/product.js";
import NoData from "@/components/NoData.vue";
import ProductItem from "@/components/ProductItem.vue";
import {PRODUCT_ROUTE} from "@/router/routes/product/product.js";

const router = useRouter()
const route = useRoute()

// 商品分类数据
const navTitle = ref('')
const categoryId = ref('')
const categorySubId = ref('')
const categoryProductList = ref([])
onBeforeMount(async () => {
  navTitle.value = route.query.categoryName + '/' + route.query.categorySubName
  categoryId.value = route.query.categoryId
  categorySubId.value = route.query.categorySubId
  // 查询商品信息
  categoryProductList.value = await getProductListRandomAPI(10, categoryId.value, categorySubId.value)
})

const productListLoading = ref(false);
const productListFinished = ref(false);
const productListError = ref(false);
const onLoadProductList = async () => {
  productListLoading.value = true
  // 异步更新数据
  const res = await getProductListRandomAPI(10, categoryId.value, categorySubId.value)
  productListLoading.value = false
  if (!res) {
    productListError.value = true
    return
  }
  categoryProductList.value.push(...res)
  // productListFinished.value = true
};
const productListRefreshing = ref(false);
const onRefreshProductList = async () => {
  // 清空数据
  categoryProductList.value = categoryProductList.value.slice(0, 10)
  // 重新加载数据
  // 异步更新数据
  const res = await getProductListRandomAPI(10, categoryId.value, categorySubId.value)
  categoryProductList.value.shift(...res)
  productListRefreshing.value = false
};

// 前往商品详情页面
const goProductDetail = (idx) => {
  // 获取商品id
  const productId = categoryProductList.value[idx].id
  router.push({
    name: PRODUCT_ROUTE,
    query: {
      productId
    }
  })
}
</script>

<template>
  <div class="category-product-list">
    <GoBack :title="navTitle" :placeholder="true" :disable-search="false"></GoBack>
    <NoData v-if="categoryProductList.length <= 0"></NoData>
    <div v-else>
      <van-pull-refresh v-model="productListRefreshing" @refresh="onRefreshProductList">
        <van-list
            v-model:loading="productListLoading"
            v-model:error="productListError"
            :finished="productListFinished"
            finished-text="没有更多了"
            error-text="请求失败，点击重新加载"
            @load="onLoadProductList"
        >
          <div
              class="box-border p-2"
              v-for="(product, idx) in categoryProductList"
              @click="goProductDetail(idx)"
          >
            <ProductItem :product="product"></ProductItem>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>